/**
 *
 * MTG Life Counter
 * Life Cell to display a player's life total
 *
 * Created by Nathan Black
 */

#import <CoreFoundation/CoreFoundation.h>
#import <GraphicsServices/GraphicsServices.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIView-Gestures.h>
#import "LifeCounterCell.h"

#define LIFE_SCROLL_SCALE 30

@implementation LifeCounterCell

int absmax(int a, int b)
{
    return (abs(a) > abs(b) ? a : b);
}

- (BOOL)ignoresMouseEvents { return NO; }
- (int)canHandleGestures { return YES; }

-initWithPlayer:(int)player game:(id)game
{
    if ((self = [super init])) {
        _game = game;
        _player = player;
    }
    return self;
}

- (void)mouseDown:(struct __GSEvent*)event 
{
    _startDrag = GSEventGetLocationInWindow(event);
    NSLog(@"mouseDown");
}

- (int)calcDelta:(struct __GSEvent*)event
{
    CGPoint p = GSEventGetLocationInWindow(event);
    // inverting y fits the up and down intuitive nature.
    _dragDelta = absmax(p.x - _startDrag.x, _startDrag.y - p.y) / LIFE_SCROLL_SCALE;
    //NSLog(@"mouseDrag: delta %d", _dragDelta);
    return _dragDelta;
}

- (void)mouseDragged:(struct __GSEvent*)event 
{
    //[self setTitle:[NSString stringWithFormat:@"%4.1f", GSEventGetDeltaY(event)]];    
    [self setTitle:[NSString stringWithFormat:@"%d", [_game playerLife:_player] + [self calcDelta:event]]];
}

- (void)mouseUp:(struct __GSEvent*)event 
{
    NSLog(@"mouseUp: delta %d", _dragDelta);
    if (_dragDelta == 0) {
        CGPoint p = [self convertPoint: GSEventGetLocationInWindow(event) fromView: nil];
        CGRect cellRect = [_layer bounds];
        int lifeChange = absmax((p.x - (cellRect.size.width / 2)), ((cellRect.size.height / 2) - p.y)) > 0 ? 1 : -1;
        [_game lifeChangeWithPlayer:_player delta:lifeChange];
        [self refresh];
    }
    else {
        [_game lifeChangeWithPlayer:_player delta:_dragDelta];
    }
    _dragDelta = 0;
}

- (void)refresh
{
    [self setTitle:[NSString stringWithFormat:@"%d", [_game playerLife:_player]]];
}

- (void)gestureChanged:(struct __GSEvent *)fp8
{
    //[self setTitle:[NSString stringWithFormat:@"%3.3f", [self zoomScale]]];    
}

@end
